import { Sprite } from "cc"
import { _decorator, Component, Node } from "cc"
import { UITransform } from "cc"
import { ClientEvent } from "../framework/ClientEvent"
import { SpriteFrame } from "cc"
const { ccclass, property } = _decorator

@ccclass("GameBossHp")
export class GameBossHp extends Component {
  @property(Node)
  nodeHp1: Node = null!

  @property(Node)
  nodeHp2: Node = null!

  @property([SpriteFrame])
  arrSprFrame: SpriteFrame[] = []

  private uiTransform1: UITransform = null

  private numCurrHp: number = 0

  private hpWidth: number = 388

  private followTarget: Node = null

  protected onLoad(): void {
    this.uiTransform1 = this.nodeHp1.getComponent(UITransform)
  }

  protected start(): void {
    this.onChangeFrame()
  }

  protected onEnable(): void {
    ClientEvent.on("onBossBeAttack", this.onBossBeAttack, this)
  }

  protected onDisable(): void {
    ClientEvent.off("onBossBeAttack", this.onBossBeAttack, this)
  }

  public init(target: Node) {
    this.followTarget = target
  }

  update(deltaTime: number) {
    const target = this.followTarget
    if (!target || !target.isValid) {
      return
    }

    this.node.positionX = target.positionX
    this.node.positionY = target.positionY + 300
  }

  private onBossBeAttack() {
    this.numCurrHp++
    if (this.numCurrHp > 100) {
      this.numCurrHp = 0
      this.onChangeFrame()
    }
    this.uiTransform1.width = this.hpWidth * (1 - 0.01 * this.numCurrHp)
  }

  indexFrame: number = 0
  private onChangeFrame() {
    this.nodeHp1.getComponent(Sprite).spriteFrame = this.arrSprFrame[this.indexFrame]

    let indexNext: number = this.indexFrame + 1
    if (indexNext >= this.arrSprFrame.length) {
      indexNext = 0
    }
    this.nodeHp2.getComponent(Sprite).spriteFrame = this.arrSprFrame[indexNext]
    this.indexFrame++
    if (this.indexFrame >= this.arrSprFrame.length) {
      this.indexFrame = 0
    }
  }
}
